import React, {useCallback, useEffect, useState} from 'react';
import {Breadcrumb, Button, Form, Input, message, Modal, Space, Table, TableProps} from 'antd';
import {useNavigate} from "react-router-dom";
import type {SkillCertificate} from "@/types/resp/skillCertificate";
import skillCertificateApi from '@/api/skillCertificateApi'
import {Result} from "@/types/result";
import {Page} from "@/types/page";
import SkillCertificateAdd from "@/pages/skillCertificate/SkillCertificateAdd.tsx";
import SkillCertificateView from "@/pages/skillCertificate/SkillCertificateView.tsx";
import CandidateSelector from "@/pages/candidate/CandidateSelector.tsx";
import { exportToExcel } from '@/utils/exportUtil.ts'



const SkillCertificateList: React.FC = () => {

  const navigate = useNavigate();
  const [messageApi, messageContextHolder] = message.useMessage();
  const [modal, modalContextHolder] = Modal.useModal();

  const handleClick = (path: string) => {
    navigate(path);
  };

  const breadcrumbsItems = [
    {title: '首页', className: 'breadcrumbHome', onClick: () => handleClick('/Home')},
    {title: '技能证书列表'}
  ]

  const [form] = Form.useForm();

  const onFinish = async () => {
    await onSearch()
  };

  const onReset = () => {
    form.resetFields();
  };

  const [data, setData] = useState<SkillCertificate[]>([]);
  const onSearch = async () => {
    try {
      const resp: Result<Page<SkillCertificate>> = await skillCertificateApi.find(form.getFieldsValue())
      if (resp && resp.code === 1) {
        if (resp.data) {
          const page: Page<SkillCertificate> = resp.data
          if (page && page.list.length > 0) {
            setData(page.list)
          }
        }
      }
    } catch (e) {
      console.log('获取数据异常', e)
    }
  };

  const columns: TableProps<SkillCertificate>['columns'] = [
    {title: '应聘者姓名', dataIndex: 'candidateName', key: 'candidateName'},
    {title: '证书名称', dataIndex: 'certificateName', key: 'certificateName'},
    {title: '颁发机构', dataIndex: 'issuingAuthority', key: 'issuingAuthority'},
    {title: '颁发时间', key: 'issueDate', render: (_, record) => (
      <div>{record.issueDate ? record.issueDate.format('YYYY-MM-DD') : ''}</div>
    )},
    {title: '到期日期', key: 'expiryDate', render: (_, record) => (
      <div>{record.expiryDate ? record.expiryDate.format('YYYY-MM-DD') : ''}</div>
    )},
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: '250px',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" onClick={() => editRow(record.id)}>编辑</Button>
          <Button danger onClick={() => delRow(record.id)}>删除</Button>
          <Button color="primary" variant="outlined" onClick={() => detailRow(record)}>详情</Button>
        </Space>
      ),
    },
  ];

  const [skillCertificateAddVisible, setSkillCertificateAddVisible] = useState(false);
  const [skillCertificateViewVisible, setSkillCertificateViewVisible] = useState(false);
  const [selectedSkillCertificateId, setSelectedSkillCertificateId] = useState(0)
  const [selectedSkillCertificate, setSelectedSkillCertificate] = useState({})

  const onAdd = () => {
    setSelectedSkillCertificateId(0)
    setSkillCertificateAddVisible(true)
  };

  const editRow = (id: number) => {
    setSelectedSkillCertificateId(id)
    setSkillCertificateAddVisible(true)
  };

  const delRow = useCallback(async (id: number) => {
    const confirmed = await modal.confirm({
      title: '删除提示',
      content: (
        <>
          确定要删除吗?
        </>
      ),
      okText: '确定',
      cancelText: '取消',
      type: 'warning'
    });

    if (confirmed) {
      skillCertificateApi.del(id)
        .then((resp) => {
          if (resp && resp.code === 1) {
            messageApi.success('删除成功!')
            onSearch()
          } else {
            messageApi.error('操作失败:' + (resp.msg ? resp.msg : '原因未知'))
          }
        })
        .catch(error => {
          console.error('操作失败:', error)
        })
    }
  }, [modal]);

  const detailRow = (record: SkillCertificate) => {
    setSelectedSkillCertificate(record)
    setSkillCertificateViewVisible(true)
  };

  const [candidateSelectorVisible, setCandidateSelectorVisible] = useState(false);
  const findCandidate = () => {
    setCandidateSelectorVisible(true);
  }
  const handleCandidateSelected = (selectedCandidate: { candidateId?: number; candidateName?: string; }) => {
    setCandidateSelectorVisible(false)
    if (selectedCandidate && 'candidateId' in selectedCandidate) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      candidateId: selectedCandidate['candidateId'],
      candidateName: selectedCandidate['candidateName'],
      }));
    }
  };
  const handleCloseCandidateSelector = () => {
    setCandidateSelectorVisible(false)
  };

  const handleCloseSkillCertificateAdd = () => {
    setSkillCertificateAddVisible(false)
  };

  const handleCloseSkillCertificateView = () => {
    setSkillCertificateViewVisible(false)
  };

  const onExport = () => {
    const headers = ['应聘者姓名','证书名称','颁发机构','颁发时间','到期日期']
    skillCertificateApi.find(form.getFieldsValue()).then(data => {
      if (!data || !data.data || data.data.list.length < 1) {
        messageApi.error('无数据导出')
        return
      }
      const exportData = []
      for (const d of data.data.list) {
        exportData.push([d.candidateName,d.certificateName,d.issuingAuthority,(d.issueDate ? d.issueDate.format('YYYY-MM-DD') : ''),(d.expiryDate ? d.expiryDate.format('YYYY-MM-DD') : '')])
      }
      exportToExcel(headers, exportData)
    })
  }

  const [findCandidateFormItem, setFindCandidateFormItem] = useState(false);
  const initByType = () => {
    const type = sessionStorage.getItem('type')
    if (type && Number(type) === 3) {
      form.setFieldsValue({
        candidateId: 2,
        candidateName: '陈静'
      });
      setFindCandidateFormItem(true)
    }
  }

  useEffect(() => {
    initByType()
    onSearch();

    return () => {
    };
  }, []);

  return (
    <div className="skillCertificateList">
      {messageContextHolder}
      {modalContextHolder}
      <Breadcrumb items={breadcrumbsItems} style={{marginBottom: 'var(--container-margin)'}} />
      <Form form={form} onFinish={onFinish} layout={"inline"}>
        <Form.Item name="candidateId">
          <Input type="hidden" />
        </Form.Item>
        <Form.Item name="candidateName" label="应聘者姓名">
          <Input.Search placeholder="请选择应聘者姓名" onSearch={findCandidate} readOnly={true} disabled={findCandidateFormItem}/>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">查询</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button onClick={onReset}>重置</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" onClick={onAdd}>新增</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" onClick={onExport}>导出</Button>
        </Form.Item>
      </Form>
      <Table<SkillCertificate> columns={columns} dataSource={data} size="small" rowKey={record => record.id} pagination={{ position: ["bottomCenter"] }} style={{marginTop: 'var(--container-margin)'}} />
      <CandidateSelector visible={candidateSelectorVisible} onCandidateSelected={handleCandidateSelected} onCloseCandidateSelector={handleCloseCandidateSelector} />
      <SkillCertificateAdd visible={skillCertificateAddVisible} onCloseSkillCertificateAdd={handleCloseSkillCertificateAdd} id={selectedSkillCertificateId} />
      <SkillCertificateView visible={skillCertificateViewVisible} onCloseSkillCertificateView={handleCloseSkillCertificateView} viewRow={selectedSkillCertificate} />
    </div>
  );
};

export default SkillCertificateList;
